// node --experimental-fetch ./.cicd/get-artifacts.js

const fs = require('fs');

// GitLab 仓库信息
const gitlabUrl = process.env.CI_SERVER_URL || 'https://code.choerodon.com.cn';
const projectName = process.env.CI_PROJECT_PATH || 'hzero-hzero-c7n-hips/hzero-front-test';
const branchName = process.env.CI_COMMIT_REF_NAME || 'test-artifacts-cache';
const jobName = process.env.CI_JOB_NAME || 'allinone-packages 1/2';

// GitLab API 访问令牌
const accessToken = process.env.MY_CI_JOB_TOKEN || process.env.CI_JOB_TOKEN || 'glpat--sGsbvu_T4ZSAxFB6mGQ';

// 下载上一次流水线作业的产物
async function downloadArtifacts(jobName) {
  try {

    console.log('Downloading artifacts...');

    const headers = { 'PRIVATE-TOKEN': accessToken };
    const downloadStream = await fetch(
      // `${gitlabUrl}/api/v4/projects/${encodeURIComponent(projectName)}/jobs/${jobId}/artifacts`,
      `${gitlabUrl}/api/v4/projects/${encodeURIComponent(projectName)}/jobs/artifacts/${encodeURIComponent(branchName)}/download?job=${encodeURIComponent(jobName)}`,
      { headers }
    );

    if(downloadStream.status >= 400) {
      throw new Error(`Error: ${downloadStream.status}, ${downloadStream.statusText}`);
    }

    const fileBuffer = await downloadStream.arrayBuffer();
    const jobId = 123;
    const filePath = `artifacts_${jobId}.zip`;
    fs.writeFileSync(filePath, Buffer.from(fileBuffer));
    console.log('Artifacts downloaded successfully.');
    return filePath;
  } catch (error) {
    console.error('Error downloading artifacts:', error.message);
    process.exit(1);
  } finally {
  }
}

const { promisify } = require('util');
const exec = promisify(require('child_process').exec);

// 解压文件到当前目录
async function unzipArtifacts(filePath) {
  try {
    console.log('Dxtract artifacts...');
    // 使用 shell 命令解压文件
    await exec(`unzip -o ${filePath}`);
    console.log('Artifacts extract successfully.');
  } catch (error) {
    console.error('Error extracting artifacts:', error.message);
    process.exit(1);
  }
}

// 主函数
async function main() {
  try {
    const filePath = await downloadArtifacts(jobName);
    if(!filePath) {
      return;
    }
    await unzipArtifacts(filePath);
    // await unzipArtifacts('artifacts_*.zip');
    process.exit(0);
  } catch (error) {
    console.error('An unexpected error occurred:', error.message);
    process.exit(0);
  }
}

// 运行主函数
main();
